<template>
  <px-dialog v-model="visible" :close-on-click-modal="false" :title="title" width="900px" destroy-on-close @close="closeDrawer">
    <px-form ref="formRef" :model="formValue" :disabled="props.drawerType === 'detail'" :rules="rules" label-width="100px">
      <px-row>
        <px-col :span="12">
          <px-form-item label="抄表类型" prop="type">
            <px-radio-group v-model="formValue.type">
              <px-radio label="0" size="large">自动抄表</px-radio>
              <px-radio label="1" size="large">手动抄表</px-radio>
            </px-radio-group>
          </px-form-item>
        </px-col>
      </px-row>
      <px-row>
        <px-col :span="12">
          <px-form-item label="抄表项名称" prop="itemName">
            <px-input v-model="formValue.itemName" placeholder="请输入抄表项名称" maxlength="50" clearable />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="抄表项Code" prop="itemCode">
            <px-input v-model="formValue.itemCode" placeholder="请输入抄表项Code" maxlength="50" clearable />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="绑定点位" prop="positionNum">
            <!-- <px-select v-model="formValue.facCode" style="width: 100%" placeholder="请选择点位进行绑定" clearable filterable>
              <px-option v-for="item in facList" :key="item.id" :label="item.name" :value="item.value" />
            </px-select> -->
            <px-input v-model="formValue.positionNum" placeholder="请输入绑定点位" clearable />
          </px-form-item>
        </px-col>
      </px-row>
      <px-row v-if="formValue.type != '1'">
        <px-col :span="12">
          <px-form-item label="周期类型" prop="periodType" :required="formValue.type == '0'">
            <px-radio-group v-model="formValue.periodType" style="width: 100%" placeholder="请选择周期类型" clearable filterable>
              <px-radio-button v-for="item in cycleList" :key="item.id" :label="item.value">{{ item.name }}</px-radio-button>
            </px-radio-group>
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="时间间隔" prop="timeInterval">
            <px-input-number v-model="formValue.timeInterval" :min="1" clearable />
          </px-form-item>
        </px-col>
      </px-row>
      <px-row>
        <px-col v-if="formValue.type != '1'" :span="12">
          <px-form-item label="开始时间" prop="startTime" :required="formValue.type == '0'">
            <px-date-picker
              v-model="formValue.startTime"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm"
              style="width: 100%"
              type="datetime"
              placeholder="请选择开始时间"
            />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="排序">
            <px-input-number v-model="formValue.sort" :min="0" />
          </px-form-item>
        </px-col>
      </px-row>
      <px-row>
        <px-col>
          <px-form-item label="备注信息">
            <px-input v-model="formValue.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" placeholder="请输入备注信息" />
          </px-form-item>
        </px-col>
      </px-row>
      <px-row>
        <px-col>
          <px-form-item label="额外信息">
            <px-input v-model="formValue.extJson" type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" placeholder="请输入额外信息" />
          </px-form-item>
        </px-col>
      </px-row>
    </px-form>
    <template #footer>
      <div v-if="drawerType === 'detail'" class="dialog-footer"><px-button @click="closeDrawer">关闭</px-button></div>
      <div v-else class="dialog-footer">
        <px-button type="primary" @click="handleSubmit(formRef)">确 定</px-button>
        <px-button @click="closeDrawer">取 消</px-button>
      </div>
    </template>
  </px-dialog>
</template>
<script setup lang="ts">
import { queryDictData } from "@/api/common";
import { addAmrItemList, updateAmrItemList } from "@/api/system/amr";
import { PxMessage } from "px-ui";
import { computed, reactive, ref, toRefs, watch } from "vue";
import { useRoute } from "vue-router";

const props = defineProps({
  // 控制弹窗显示隐藏
  visible: {
    type: Boolean,
    default: false
  },
  // 弹窗类型 view 查看 add 新增 edit 编辑
  drawerType: {
    type: String,
    default: "add"
  },
  // 表单数据
  detailsData: {
    type: Object,
    default() {
      return {};
    }
  }
});

const route = useRoute();
const visible = computed(() => props.visible);
const title = computed(() => {
  const { drawerType } = props;
  if (drawerType === "add") {
    return "新增抄表项";
  } else if (drawerType === "edit") {
    return "编辑抄表项";
  } else {
    return "抄表项详情";
  }
});

// 调用父级-关闭抽屉、查询列表方法
const emits = defineEmits(["closeDrawer", "queryTable"]);

const queryClassNameSelect = async () => {
  cycleList.value = await queryDictData({ typeCode: "METER_READING_ITEM_TYPE" });
};
const formRef = ref();
const valueIsEmpty = value => {
  if (value === "" || value == null || typeof value == "undefined") {
    return true;
  }
  return false;
};
const checkPeriodType = (rule, value, callback) => {
  if (formValue.value.type == "1") {
    callback();
  } else {
    if (valueIsEmpty(value)) {
      return callback(new Error("周期类型不能为空"));
    } else {
      callback();
    }
  }
};
const checkTimeInterval = (rule, value, callback) => {
  if (formValue.value.type == "1") {
    callback();
  } else {
    if (valueIsEmpty(value)) {
      return callback(new Error("时间间隔不能为空"));
    } else {
      callback();
    }
  }
};
const checkStartTime = (rule, value, callback) => {
  if (formValue.value.type == "1") {
    callback();
  } else {
    if (valueIsEmpty(value)) {
      return callback(new Error("开始时间不能为空"));
    } else {
      callback();
    }
  }
};
const data = reactive<Record<string, any>>({
  formValue: {
    sort: 0,
    timeInterval: 1,
    type: "0"
  },
  rules: {
    itemName: [{ required: true, message: "抄表项名称不能为空", trigger: "blur" }],
    itemCode: [{ required: true, message: "抄表项Code不能为空", trigger: "blur" }],
    positionNum: [{ required: true, message: "绑定点位不能为空", trigger: "change" }],
    periodType: [{ validator: checkPeriodType, trigger: "change" }],
    timeInterval: [{ validator: checkTimeInterval, trigger: "change" }],
    startTime: [{ validator: checkStartTime, trigger: "change" }]
  },
  cycleList: []
});

const { formValue, rules, cycleList } = toRefs(data);

watch(
  () => props.visible,
  (newVal, oldVal) => {
    console.log(newVal, oldVal);
    if (newVal) {
      queryClassNameSelect();
      if (props.drawerType !== "add") {
        formValue.value = JSON.parse(JSON.stringify(props.detailsData));
        formValue.value.type = formValue.value.type + "";
      }
    }
  }
);

// 关闭抽屉
const closeDrawer = () => {
  formRef.value.resetFields();
  formValue.value = {};
  formValue.value = {
    sort: 0,
    timeInterval: 1,
    type: "0"
  };
  emits("closeDrawer");
};
// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const params = formValue.value;
      if (props.drawerType === "add") {
        await addAmrItemList({ groupId: route.query.id, groupCode: route.query.code, ...params });
        PxMessage.success("新增成功");
        closeDrawer();
        emits("queryTable");
      } else if (props.drawerType === "edit") {
        await updateAmrItemList({ groupId: route.query.id, groupCode: route.query.code, ...params });
        PxMessage.success("编辑成功");
        closeDrawer();
        emits("queryTable");
      }
    }
  });
};
</script>
